use crate::{common, tables::applog::TbAppLog};
use actix_web::{get, web, Responder};
use rbdc::datetime::DateTime;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct Get {
    log_type: Option<u32>,
    ip: Option<String>,
    text: Option<String>,
    begin_time: Option<DateTime>,
    end_time: Option<DateTime>,
}

#[get("")]
async fn get(page: web::Query<common::QueryPage>, query: web::Query<Get>) -> impl Responder {
    common::ResData::<TbAppLog>::from_page(TbAppLog::get_applogs(&page, &query).await).resp_json()
}

pub fn routes(cfg: &mut web::ServiceConfig) {
    cfg.service(web::scope("/applog").service(get));
}

#[cfg(test)]
pub mod tests {
    use crate::{handlers::applog, utils::mysql};
    use actix_web::{test, App};
    use serde_json::Value;

    #[actix_web::test]
    async fn test_get_applogs() {
        mysql::init_pool().await;

        let app = test::init_service(App::new().configure(applog::routes)).await;

        let req = test::TestRequest::get()
            .uri("/applog?begin_time=2021-10-25+13%3A30%3A00")
            .to_request();

        let resp = test::call_service(&app, req).await;
        let status = resp.status();
        println!("resp status is {:?}", status);
        let resp_body = test::read_body(resp).await;
        let json_value: Value = serde_json::from_slice(&resp_body).unwrap();
        println!("restp body is {:?}", json_value);
        assert!(status.is_success());
    }
}
